import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

typedef AddresssCallback = void Function();

class AddresssPopView extends StatefulWidget {
  final String url;
  final AddresssCallback? onSaveSuccess;
  final double viewHeight;
  final bool visible; // 👈 添加外部控制变量
  final VoidCallback? onDismiss; // 👈 添加蒙层点击回调（关闭）

  const AddresssPopView({
    Key? key,
    required this.url,
    this.onSaveSuccess,
    this.viewHeight = 610.0,
    required this.visible,
    this.onDismiss,
  }) : super(key: key);

  @override
  State<AddresssPopView> createState() => _AddresssPopViewState();
}

class _AddresssPopViewState extends State<AddresssPopView> {
  late final WebViewController _controller;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel(
        'appBillingBack',
        onMessageReceived: (message) {
          widget.onSaveSuccess?.call(); // 回调通知
          widget.onDismiss?.call(); // 关闭蒙层
        },
      )
      ..addJavaScriptChannel(
        'appBillingCancel',
        onMessageReceived: (message) {
          widget.onDismiss?.call(); // 关闭蒙层
        },
      )
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (url) => setState(() => _isLoading = true),
          onPageFinished: (url) => setState(() => _isLoading = false),
          onWebResourceError: (_) => setState(() => _isLoading = false),
        ),
      )
      ..loadRequest(Uri.parse(widget.url));
  }

  @override
  void didUpdateWidget(covariant AddresssPopView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.url != oldWidget.url && widget.url.isNotEmpty) {
      _controller.loadRequest(Uri.parse(widget.url));
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.visible) return const SizedBox.shrink(); // 👈 不显示时直接返回空视图

    return Positioned.fill(
      child: Material(
        color: Colors.black.withOpacity(0.5), // 👈 半透明蒙层
        child: GestureDetector(
          onTap: widget.onDismiss, // 👈 点击蒙层关闭
          child: Stack(
            children: [
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: GestureDetector(
                  onTap: () {}, // 👈 阻止点击穿透
                  child: Container(
                    height: widget.viewHeight,
                    decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
                    ),
                    child: Stack(
                      children: [
                        ClipRRect(
                          borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
                          child: WebViewWidget(controller: _controller),
                        ),
                        if (_isLoading)
                          const Center(child: CircularProgressIndicator()),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
